<!-- 实现canvas手写签名组件 -->
<template>
  <div class="hand-written-signature">
    <canvas ref="canvas" :width="width" :height="height"></canvas>
    <div class="hand-written-signature__btns">
      <button @click="clear">清空</button>
      <button @click="save">保存</button>
    </div>
  </div>
</template>

<script setup>
import { onMounted } from 'vue'
const canvas = ref(null)
const ctx = ref(null)
const width = ref(500)
const height = ref(200)
let drawing = false
let lastPoint = { x: 0, y: 0 }

// emit
const emit = defineEmits(['save'])
// 开始签名
const startDrawing = (e) =>{
  e.preventDefault()
  drawing = true
  lastPoint = { x: e.offsetX, y: e.offsetY }
}
// 停止输入
const stopDrawing = () => {
  drawing = false
  ctx.value.beginPath()
  // ctx.value.stroke()
}
// 输入中
const draw = (e) => {
  if(!drawing) return
  ctx.value.beginPath() 
  ctx.value.moveTo(lastPoint.x, lastPoint.y)
  const currentPoint = { x: e.offsetX, y: e.offsetY }
  const minPoint = midpoint(lastPoint, currentPoint)
  ctx.value.quadraticCurveTo( minPoint.x, minPoint.y,currentPoint.x,currentPoint.y)
  
  lastPoint = currentPoint
  // 优化绘制路径
  // requestAnimationFrame(() => {
  //   ctx.value.stroke()
  // })
  ctx.value.stroke()
}

const midpoint = (pt1, pt2) => {
  return {
    x: (pt1.x + pt2.x) / 2,
    y: (pt1.y +pt2.y) / 2
  }
}
onMounted(() => {
  ctx.value = canvas.value.getContext('2d')
  ctx.value.lineWidth = 5
  ctx.value.strokeStyle = 'black'
  ctx.value.lineCap = 'round'
  ctx.value.lineJoin = 'round'

  canvas.value.addEventListener('mousedown', startDrawing)
  canvas.value.addEventListener('mouseup', stopDrawing)
  canvas.value.addEventListener('mouseout', stopDrawing)
  canvas.value.addEventListener('mousemove', draw)
})

const clear = () => {
  ctx.value.clearRect(0, 0, width.value, height.value)
}

const save = () => {
  const dataURL = canvas.value.toDataURL('image/png')
  emit('save', dataURL)
}



</script>

<style scoped>
.hand-written-signature {
  border: 1px solid #ccc;
  border-radius: 4px;
  overflow: hidden;
  width: 500px;
}

.hand-written-signature__btns {
  display: flex;
  justify-content: center;
  margin-top: 10px;
  margin-bottom: 10px;
}

.hand-written-signature__btns button {
  padding: 6px 12px;
  margin: 0 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  background-color: #fff;
  cursor: pointer;
  user-select: none;
}

.hand-written-signature__btns button:hover {
  background-color: #f5f5f5;
}

.hand-written-signature__btns button:active {
  background-color: #e9e9e9;
}

.hand-written-signature__btns button:focus {
  outline: none;
}

.hand-written-signature__btns button:first-child {
  margin-left: 0;
}

.hand-written-signature__btns button:last-child {
  margin-right: 0;
 
}

</style>